<?php 
/**
 * Provide navigation sidebar functionality to Dokuwiki Templates
 *
 * @author Christopher Smith <chris@jalakai.co.uk>
 * @author Esther Brunner <wikidesign@gmail.com>
*  @author Stephane Chamberland <stephane.chamberland@gmail.com>
 */

/**
 * Recursive function to establish best sidebar file to be used
 */
function getSidebarFN($ns, $file){

	// check for wiki page = $ns:$file (or $file where no namespace)
	$nsFile = ($ns) ? "$ns:$file" : $file;
	if (@file_exists(wikiFN($nsFile)) && auth_quickaclcheck($nsFile)) return $nsFile;
	
  // remove deepest namespace level and call function recursively
	
	// no namespace left, exit with no file found	
	if (!$ns) return '';
	
	$i = strrpos($ns, ":");
	$ns = ($i) ? substr($ns, 0, $i) : false;	
	return getSidebarFN($ns, $file);
}

/**
 * Display the sidebar
 */
function tpl_sidebar(){
	global $ID, $REV, $conf;
	
	// save globals
	$saveID = $ID;
	$saveREV = $REV;

	// discover file to be displayed in navigation sidebar	
  $fileSidebar = getSidebarFN(getNS($ID), tpl_getConf('sidebar_page'));

	// determine what to display
	if ($fileSidebar){
		$ID = $fileSidebar;
		$REV = '';
		print p_wiki_xhtml($ID,$REV,false);
	} else {
    global $IDX;
    html_index($IDX);
	}
		
	// restore globals
	$ID = $saveID;
	$REV = $saveREV;
}
/**
 * 
 */
function tpl_menu(){
	$mymenu = tpl_getmenulinks('menu');
	if (is_array($mymenu)) $mysubmenu = tpl_topbar2($mymenu);
	if (is_array($mysubmenu)) tpl_tabs2($mysubmenu);
}

function tpl_menu_foot() {
	$mymenu = tpl_getmenulinks('menu');
	$out = '<div class="foot_menu"><div><ul>';
	foreach ($mymenu as $menuitem){
		$id    = $menuitem['id'];
		if ($id != 'en:home' && $id != 'fr:home') {
		$title = $menuitem['title'];
		$wl   = wl($id);
		$out .= '<li><a href="'.$wl.'" class="'.$myclass.'">'.$title.'</a>';
		if (isset($menuitem['submenu'])) {
			$out .= '<ul>';
			foreach ($menuitem['submenu'] as $menuitem2){
				$id    = $menuitem2['id'];
				$wl2   = wl($id);
				if ($wl != $wl2) {
					$title = $menuitem2['title'];
					$out .= '<li><a href="'.wl($id).'" class="'.$myclass.'">'.$title.'</a></li>';
				}
			}
			$out .= '</ul>';
		}
		$out .= '</li>';
		}
	}
	$out .= '</ul></div></div>';
	echo $out;
}

function tpl_getmenulinks($menufilename = 'menu'){
	global $ID;
  	$out = '';
 
  	// discover file to be displayed in navigation sidebar	
  	$tabsFile = getSidebarFN(getNS($ID), $menufilename);
	// determine what to display
	if (@file_exists(wikiFN($tabsFile))){
		//Collect list items
        $ins = p_cached_instructions(wikiFN($tabsFile));
		$mymenu  = array();
		$mylevel = 0;
        foreach ($ins as $in){
			if ($in[0] == 'listu_open') {
				$mylevel = $mylevel + 1;
				if ($mylevel <= 2) $mysubmenu = array();
			} else if ($in[0] == 'listu_close') {
				if ($mylevel == 2) $mymenu[count($mymenu)-1]['submenu'] = $mysubmenu;
				$mylevel = $mylevel - 1;
			} else if ($in[0] == 'internallink' && $mylevel > 0) {
				list($id, $hash) = explode('#', $in[1][0], 2);
				resolve_pageid(getNS($ID), $id, $exists);
				$title = hsc($in[1][1]);
				if (!$title) $title = hsc(p_get_first_heading($id));
				if (!$title) $title = hsc(ucwords(noNS($id)));
				if ($mylevel == 1) {
					$mymenu[] = array(
						'id' => $id,
						'title' => $title,
						);
				} else if ($mylevel == 2) {
					$mysubmenu[] = array(
						'id' => $id,
						'title' => $title,
						);
				}
			}
		}
	} else {
		return false;
	}
	return $mymenu;
}

/**
 * Display the topbar
 */
function tpl_topbar2($menuarray){
	global $ID;
  	$out = '';
	$mysubmenu = '';
	$ns = getNS($ID);
	foreach ($menuarray as $menuitem){
		$id    = $menuitem['id'];
		$title = $menuitem['title'];
		//check that $ID is under getNS($id);
		$ns2 = getNS($id);
		$isIn = false;
		if (substr(rtrim($id), -1) == ":") {
			while (!$isIn && $ns) {
				if (strtolower($ns) == strtolower($ns2)) $isIn = true;
				$ns = getNS($ns);
			}
		} else if ($ns == $ns2) {
			$isIn = true;
		} else {
			if (strtolower($ID) == strtolower($id)) $isIn = true;
		}
		$myclass = "toptab";
		if ($isIn) {
			$myclass = "activetoptab";
		}
		//$out .= '<div style="display:inline;">';
		$out .= '<a href="'.wl($id).'" class="'.$myclass.'">'.$title.'</a>';
		if (isset($menuitem['submenu'])) {
			if ($isIn) {
				$mysubmenu = $menuitem['submenu'];
			//} else {
				//$out .= '<div style="display:none;">';
				//foreach($menuitem['submenu'] as $submenuitem) {
				//	$out .= '<a href="'.wl($submenuitem['id']).'" class="submenuitem">'.$submenuitem['title'].'</a><br />';
				//}
				//$out .= '</div>';
			}
		}
		//$out .= '</div>';
	}
	echo '<div class="topbar">'.$out.'</div>';
	if (is_array($mysubmenu)) return $mysubmenu;
	return false;
}

/**
 * Return the correct ID for <div class="dokuwiki">
 */
function tpl_classID(){
  echo 'minima__'.tpl_getConf('width').'_'.tpl_getConf('sidebar_position');
}

/**
 * Display tabs for easy navigation
 */
function tpl_tabs2($menuarray){
	global $ID;
  	$out = '';
	$mysubmenu = '';
	$ns = getNS($ID);
	foreach ($menuarray as $menuitem){
		$id    = $menuitem['id'];
		$title = $menuitem['title'];
       // now construct the output link
        if ($id == $ID) $out .= '<span class="activetab">'.$title.'</span> ';
        else $out .= '<a href="'.wl($id).'" class="tab">'.$title.'</a> ';
	}
    echo '<div class="tabs">'.$out.'</div>';
}

/**
 *  
 */
 function get_lang_from_id($id) {
    $ns = getNS($id);
    $top_ns = '';
    while ($ns) {
        $top_ns = $ns;
        $ns = getNS($ns);
    }
    if ($top_ns != 'en') return 'fr';
    return 'en';
}

function set_id_from_lang() {
}

function echo_lang_switch_link($id) {
    global $conf;
    if ($conf['lang'] != 'en') {
        $id = preg_replace('/^fr(:.*)/','en$1',$id);
        //$id2 = explode(':',$id);
        //$id2[0] = 'fr';
        //$id = implode(':',$id2);
        tpl_link (wl($id),'English',"alt='$id'");
    } else {
        $id = preg_replace('/^en(:.*)/','fr$1',$id);
        //$id2 = explode(':',$id);
        //$id2[0] = 'fr';
        //$id = implode(':',$id2);
        tpl_link (wl($id),'Français',"alt='$id'");
    }
}

function set_lang_from_id($id) {
    global $conf,$lang;
    $lang2 = get_lang_from_id($id);
    if ($lang2 != $conf['lang']) {
        $conf['lang'] = $lang2;
        @include(DOKU_INC.'inc/lang/'.$conf['lang'].'/lang.php');
    }
}
 
 /**
 * Hierarchical breadcrumbs
 *
 * This code was suggested as replacement for the usual breadcrumbs.
 * It only makes sense with a deep site structure.
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Nigel McNie <oracle.shinoda@gmail.com>
 * @author Sean Coates <sean@caedmon.net>
 * @author Stephane Chamberland <stephane.chamberland@gmail.com> : skip startpage for multi-lang wiki
 * @link   http://wiki.splitbrain.org/wiki:tipsandtricks:hierarchicalbreadcrumbs
 * @todo   May behave strangely in RTL languages
 */
function tpl_youarehere2($sep=' &raquo; '){
  global $conf;
  global $ID;
  global $lang;

  // check if enabled
  if(!$conf['youarehere']) return false;

  $parts = explode(':', $ID);
  $count = count($parts);

  if ($count < 2 || $parts[1] == strtolower($conf['start'])) return false;

  echo $lang['youarehere'].': ';

  // always print the startpage
  //$title = p_get_first_heading($conf['start']);
  //if(!$title) $title = $conf['start'];
  //tpl_link(wl($conf['start']),hsc($title),'title="'.$conf['start'].'"');

  // print intermediate namespace links
  $part = '';
  for($i=0; $i<$count - 1; $i++){
    $part .= $parts[$i].':';
    $page = $part;
    resolve_pageid('',$page,$exists);
    if ($page == $conf['start']) continue; // Skip startpage 

    // output
    if ($i > 0) echo $sep;
    if($exists){
      $title = p_get_first_heading($page);
      if(!$title) $title = $parts[$i];
      tpl_link(wl($page),hsc($title),'title="'.$page.'"');
    }else{
      tpl_link(wl($page),$parts[$i],'title="'.$page.'" class="wikilink2"');
    }
  }

  // print current page, skipping start page, skipping for namespace index
  if(isset($page) && $page==$part.$parts[$i]) return;
  $page = $part.$parts[$i];
  if($page == $conf['start']) return;
  echo $sep;
  if(@file_exists(wikiFN($page))){
    $title = p_get_first_heading($page);
    if(!$title) $title = $parts[$i];
    tpl_link(wl($page),hsc($title),'title="'.$page.'"');
  }else{
    tpl_link(wl($page),$parts[$i],'title="'.$page.'" class="wikilink2"');
  }
  return true;
}
